package io.github.xbeeant.eoffice.rest;

import io.github.xbeeant.antdesign.TableResponse;
import io.github.xbeeant.core.ApiResponse;
import io.github.xbeeant.core.ErrorCodeConstant;
import io.github.xbeeant.eoffice.antdesign.TreeNode;
import io.github.xbeeant.eoffice.model.*;
import io.github.xbeeant.eoffice.rest.vo.DocTemplateCatVo;
import io.github.xbeeant.eoffice.service.IAttachmentService;
import io.github.xbeeant.eoffice.service.IDocTemplateCatService;
import io.github.xbeeant.eoffice.service.IDocTemplateService;
import io.github.xbeeant.eoffice.util.SecurityHelper;
import io.github.xbeeant.spring.mybatis.antdesign.PageRequest;
import io.github.xbeeant.spring.mybatis.antdesign.PageResponse;
import io.github.xbeeant.spring.security.LoginUser;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaobiao
 * @version 2021/7/8
 */
@RestController
@RequestMapping("api/templates")
public class TemplatesRestController {

    @Autowired
    private IDocTemplateCatService templateCatService;

    @Autowired
    private IDocTemplateService templateService;

    @Autowired
    private IAttachmentService attachmentService;

    @GetMapping
    public ApiResponse<List<DocTemplateCatVo>> fetch(Integer type) {
        ApiResponse<List<DocTemplateCatVo>> result = new ApiResponse<>();
        LoginUser<User> userLoginUser = SecurityHelper.currentUser();
        result.setData(templateCatService.fetch(type, userLoginUser.getUserId()));
        return result;
    }

    @GetMapping("list")
    public ApiResponse<TableResponse<DocTemplate>> list(DocTemplate template, PageRequest pageRequest) {
        ApiResponse<TableResponse<DocTemplate>> apiResponse = new ApiResponse<>();
        PageRequest webRequest = new PageRequest(pageRequest);

        ApiResponse<PageResponse<DocTemplate>> list = templateService.fuzzySearchByPager(template, webRequest.getPageBounds());
        if (!list.getSuccess()) {
            apiResponse.setResult(ErrorCodeConstant.NO_MATCH, ErrorCodeConstant.NO_MATCH_MSG);
            return apiResponse;
        }

        TableResponse<DocTemplate> pageResponse = new TableResponse<>();
        pageResponse.setList(list.getData());
        pageResponse.setPagination(list.getData().getPagination());
        apiResponse.setData(pageResponse);
        return apiResponse;
    }

    @GetMapping("cat")
    public List<TreeNode> cats() {
        LoginUser<User> userLoginUser = SecurityHelper.currentUser();
        List<DocTemplateCat> cats = templateCatService.cats(userLoginUser.getUserId());

        // 分组
        //  1:word文档   2:excel文档 3.PowerPoint文档
        List<TreeNode> treeNodes = new ArrayList<>(3);

        TreeNode word = new TreeNode();
        word.setKey(1L);
        word.setTitle("Word");
        treeNodes.add(word);

        TreeNode excel = new TreeNode();
        excel.setKey(2L);
        excel.setTitle("Excel");
        treeNodes.add(excel);

        TreeNode ppt = new TreeNode();
        ppt.setKey(3L);
        ppt.setTitle("PPT");
        treeNodes.add(ppt);

        if (!CollectionUtils.isEmpty(cats)) {
            TreeNode treeNode;
            for (DocTemplateCat cat : cats) {
                treeNode = new TreeNode();
                treeNode.setTitle(cat.getName());
                treeNode.setKey(cat.getCid());
                treeNode.setCode(String.valueOf(cat.getIsPrivate()));
                treeNode.setExtra(String.valueOf(cat.getType()));
                switch (cat.getType()) {
                    case 1:
                        word.addChildren(treeNode);
                        break;
                    case 2:
                        excel.addChildren(treeNode);
                        break;
                    default:
                        ppt.addChildren(treeNode);
                        break;
                }
            }
        }

        return treeNodes;
    }

    @PostMapping("cat")
    public ApiResponse<DocTemplateCat> addCat(DocTemplateCat record) {
        record.emptySensitiveInfo();
        record.setIsPrivate(true);
        return templateCatService.insertSelective(record);
    }

    @PostMapping("share")
    public ApiResponse<DocTemplate> share(Long tid, Boolean isPrivate) {
        ApiResponse<DocTemplate> docTemplateApiResponse = templateService.selectByPrimaryKey(tid);
        LoginUser<User> userLoginUser = SecurityHelper.currentUser();
        if (!userLoginUser.getUserId().equals(docTemplateApiResponse.getData().getCreateBy())) {
            ApiResponse<DocTemplate> result = new ApiResponse<>();
            result.setResult(1, "该模板不是您上传的，无法修改分享状态");
            return result;
        }

        DocTemplate record = new DocTemplate();
        record.setTid(tid);
        record.setIsPrivate(isPrivate);
        return templateService.updateByPrimaryKeySelective(record);
    }

    @PostMapping("upload")
    public ApiResponse<String> upload(MultipartFile file, DocTemplate record) throws IOException, NoSuchAlgorithmException {
        ApiResponse<String> result = new ApiResponse<>();

        LoginUser<User> user = SecurityHelper.currentUser();
        Attachment attachment = attachmentService.save(file, user.getUserId());

        if (record.getTid() != null ) {
            // 更新模板
            DocTemplate docTemplate = new DocTemplate();
            docTemplate.setAid(attachment.getAid());
            docTemplate.setTid(record.getTid());
            docTemplate.setTitle(attachment.getFilename());
            templateService.updateByPrimaryKeySelective(docTemplate);
        } else {
            // 写入模板的文件信息
            DocTemplate docTemplate = new DocTemplate();
            docTemplate.setAid(attachment.getAid());
            docTemplate.setCid(record.getCid());
            docTemplate.setTitle(attachment.getFilename());
            templateService.insertSelective(docTemplate);
        }


        return result;
    }
}
